<template>
<el-container class="map">
    <el-aside width="300px">
        <el-tabs v-model="activeName" class="border-card" :stretch="true" @tab-click="tabClick">
            <el-tab-pane label="采集中" name="underway">
                <AcquisitionTask status="underway" :key="random" :taskObject="taskObject" :currentTask="currentTask" :PropsLoading="loading" @filterMap="getFilterMap" :userInfo="userInfo" v-if="activeName === 'underway'"></AcquisitionTask>
            </el-tab-pane>
            <el-tab-pane label="已到期" name="underwayend">
                <AcquisitionTask status="underwayend" :taskObject="taskObject" :userInfo="userInfo" :currentTask="currentTask" :PropsLoading="loading" @filterMap="getFilterMap" v-if="activeName === 'underwayend'"></AcquisitionTask>
            </el-tab-pane>
            <el-tab-pane label="数据查看" name="dataview">
                <DataView></DataView>
            </el-tab-pane>
        </el-tabs>
    </el-aside>
    <el-container>
        <el-header class="tool">
            <div>
                <CreateTask class="li" type="primary" icon="el-icon-arrow-right el-icon--right" label="创建任务计划">区镇级管理员 / 创建任务计划</CreateTask>
                <el-button class="li" @click="guidance(0)" type="primary" icon="el-icon-share">任务执行 / 数据标注 / 村居采集 , 镇 / 街区支持录入<i class="el-icon-arrow-right el-icon--right"></i></el-button>
                <el-button class="li" @click="guidance(1)" type="primary" icon="el-icon-s-opportunity">任务数据查看 / 审核 / 镇街审核 / 区支持审核</el-button>
            </div>
            <div>
                <el-button class="li" style="display: none;" @click="openlayersShow = !openlayersShow" type="warning">{{openlayersShow?'2018土地利用现状':'回到GIS控制台'}}</el-button>
            </div>
        </el-header>
        <el-main>
            <sm-web-map @load="mapLoad" v-if="openlayersShow" class="sm-web-map" :map-options="mapOptions">
                <Toolbar v-if="map"></Toolbar>
                <search v-if="map"></search>
                <MapState v-if="map" :taskObject="taskObject" @on-filterMap="mapFilterState" @on-select-map="selectRegion" @on-change="mapStateChange" :currentTask="currentTask" :userInfo="userInfo" :SearchMap="SearchMap"></MapState>
                <el-dialog :title="currentDataTaskPlanName" :visible.sync="LandParcelInfoVisible" width="65%">
                    <!-- <PlotMsg :LandParcelInfo="LandParcelInfo" :subjectData="subjectData" :currentTask="currentTask" @on-collect="collectSuccess" /> -->
                    <AcquisitionInterface :remoteSensingData="remoteSensingData" :currentTask="currentTask" :isShow="isShow" :spotID="spotID" :userInfo="userInfo">图斑信息采集界面</AcquisitionInterface>
                </el-dialog>
                <el-dialog title="批量操作" :visible.sync="batchShow" width="70%">
                    <batch :currentTask="currentTask" :subjectData="subjectData" :mapland="maplandList" :batchrandom="batchrandom" :maplandListpage="maplandListpage">批量</batch>
                </el-dialog>
                <sm-scale :position="position">比例尺</sm-scale>
                <sm-compass :position="position">指南针</sm-compass>
                <sm-zoom :position="position">缩放</sm-zoom>
                <sm-measure headerName="框选批量服务" @click.native="experimentalDataAreaLayer" :position="position">测量算距</sm-measure>
                <!-- <sm-draw headerName="框选批量服务" :draw-created="drawCreated" :position="position">框选批量服务</sm-draw> -->
                <sm-coordinate-conversion :position="position" :collapsed="true">经纬度坐标转换</sm-coordinate-conversion>
                <sm-layer-color :position="position">图层颜色</sm-layer-color>
                <!-- <sm-tdt-route :position="position" :data="{ tk: tiandituToken }">路线查询</sm-tdt-route> -->
            </sm-web-map>
            <openlayers v-else></openlayers>
        </el-main>
    </el-container>
</el-container>
</template>

<script>
const mapsettings = require("@/mapsettings.js");
let {
    serverUrl,
    tiandituUrl,
    gisUrl,
    dark,
    YJLX_CODEfillcolor,
    EJLX_CODEfillcolor,
    linecolor,
    tiandituToken,
    center,
    zoom,
} = mapsettings;
import {
    mapState
} from "vuex";
import axios from "axios";
export default {
    components: {
        Toolbar: () => import("@/views/Map/Toolbar/Toolbar.vue"),
        openlayers: () => import("@/views/openlayers/openlayers.vue"),
        MapState: () => import("./MapState/MapState.vue"),
        AcquisitionTask: () => import("./left/AcquisitionTask/AcquisitionTask.vue"),
        DataView: () => import("./left/DataView/DataView.vue"),
        PlotMsg: () => import("@/components/PlotMsg/PlotMsg.vue"),
        search: () => import("./search/search.vue"),
        batch: () => import("./batch/batch.vue"),
        relevancy: () => import("@/components/PlotMsg/relevancy/relevancy.vue"),
    },
    data() {
        return {
            isShow: true,
            remoteSensingData: {},
            spotID: "",
            currentDataTaskPlanName: "",
            openLayerText: "2018土地利用",
            openlayersShow: true,
            subjectData: [],
            landCodeArray: [],
            random: 0,
            batchrandom: 0,
            maplandList: [],
            maplandListpage: {},
            "experimentalData-area-layer": false,
            batchShow: false,
            spotstate: null,
            SYS_TYPE: "",
            loading: false,
            activeName: "underway",
            LandParcelInfo: {},
            LandParcelInfoVisible: false,
            map: null,
            tiandituToken: tiandituToken,
            position: "bottom-right",
            DKBHID: [],
            SearchMapArray: [],
            center: center,
            zoom: zoom,
            mapOptions: {
                center: center,
                zoom: zoom,
                maxZoom: 24,
                style: {
                    version: 8,
                    sources: {
                        "raster-tiles": {
                            type: "raster",
                            tiles: [
                                `${serverUrl}/iserver/services/map-china400/rest/maps/${dark}/zxyTileImage.png?z={z}&x={x}&y={y}`,
                            ],
                            tileSize: 256,
                        },

                        // labelLayer_img: {
                        //     type: "raster",
                        //     tiles: [
                        //         `${tiandituUrl}/cia_w/wmts?tk=53601310a9c2ea79748468191c57382a&service=WMTS&request=GetTile&version=1.0.0&style=default&tilematrixSet=w&format=tiles&width=256&height=256&layer=cia&tilematrix={z}&tilerow={y}&tilecol={x}`,
                        //     ],
                        //     tileSize: 256,
                        // },
                        // labelLayer_vec: {
                        //     type: "raster",
                        //     tiles: [
                        //         `${tiandituUrl}/cva_w/wmts?tk=53601310a9c2ea79748468191c57382a&service=WMTS&request=GetTile&version=1.0.0&style=default&tilematrixSet=w&format=tiles&width=256&height=256&layer=cva&tilematrix={z}&tilerow={y}&tilecol={x}`,
                        //     ],
                        //     tileSize: 256,
                        // },
                        // 南海区遥感地图
                        nanhai: {
                            type: "raster",
                            tiles: [
                                `${gisUrl}/geoserver/gwc/service/wmts?SERVICE=WMTS&REQUEST=GetTile&LAYER=nanhai:nanhaiquPhase1Image&TILEMATRIX=EPSG:900913:{z}&TILEMATRIXSET=EPSG:900913&format=image%2Fpng&TileCol={x}&TileRow={y}`,
                            ],
                            tileSize: 256,
                        },

                        // //加载2018土地底图图层 // 2018 发布政务云内网的时候开启
                        // wms_layer: {
                        //     'type': 'raster', //图层类型
                        //     'tiles': [
                        //         //这里可以设置各个图层lw_base_mapbox 
                        //         'http://10.171.142.15:8080/GISServices/spService/cfb7457737d841efs28daffa2d058e7800/services/map-GT_TDLYXZ2018/wms111/TDLYXZ2018_CGCS2000?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=TDLYXZ2018_CGCS2000' //wms地图服务地
                        //     ],
                        //     'tileSize': 512 //图片显示的大小，最好和上面大小保持一致
                        // },
                        // //加载村界底图图层 // 2018 发布政务云内网的时候开启
                        // SQCJBJ: {
                        //     'type': 'raster', //图层类型
                        //     'tiles': [
                        //         //这里可以设置各个图层lw_base_mapbox 
                        //         'http://10.171.142.15:8080/GISServices/spService/cfb7457737d841efs28daffa2d058e7800/services/map-NH_ZS_XZJX_CGCS2000/wms111/NH_SQCJBJ_CGCS2000?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=NH_SQCJBJ_CGCS2000' //wms地图服务地
                        //     ],
                        //     'tileSize': 512 //图片显示的大小，最好和上面大小保持一致
                        // },

                        nanhai_village: {
                            type: "vector",
                            scheme: "tms",
                            tiles: [
                                `${gisUrl}/geoserver/gwc/service/tms/1.0.0/nanhai%3Ananhai_village@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf`,
                            ],
                        },
                        //图斑数据信息
                        experimental: {
                            type: "vector",
                            scheme: "tms",
                            tiles: [
                                `${gisUrl}/geoserver/gwc/service/tms/1.0.0/nanhai%3Aexperimental@EPSG%3A900913@pbf/{z}/{x}/{y}.pbf`,
                            ],
                        },
                    },
                    layers: [{
                            id: "raster-tiles",
                            type: "raster",
                            source: "raster-tiles",
                        },

                        // {
                        //     id: "labelLayer_img",
                        //     type: "raster",
                        //     source: "labelLayer_img",
                        // },
                        // {
                        //     id: "labelLayer_vec",
                        //     type: "raster",
                        //     source: "labelLayer_vec",
                        // },

                        {
                            id: "nanhai",
                            type: "raster",
                            source: "nanhai",
                        },
                        // // 2018 发布政务云内网的时候开启
                        // {
                        //     "id": "wms_layer",
                        //     "type": "raster",
                        //     "source": "wms_layer",
                        //     "minzoom": 0,
                        //     "maxzoom": 22,
                        //     'paint': {
                        //         "raster-opacity": .5,
                        //     }
                        // },
                        //图斑
                        {
                            id: `experimental-area-layer`,
                            source: `experimental`,
                            "source-layer": `experimental`,
                            type: "fill",
                            paint: {
                                "fill-color": EJLX_CODEfillcolor,
                                "fill-opacity": 1,
                            },
                        },

                        //图斑边缘
                        {
                            id: `experimental-line-layer`,
                            source: `experimental`,
                            "source-layer": `experimental`,
                            type: "line",
                            layout: {
                                "line-cap": "round",
                                "line-join": "round",
                            },
                            paint: {
                                // "line-color": linecolor,
                                "line-opacity": 1,
                            },
                        },
                        // 2018 发布政务云内网的时候开启
                        // {
                        //     "id": "SQCJBJ",
                        //     "type": "raster",
                        //     "source": "SQCJBJ",
                        //     "minzoom": 0,
                        //     "maxzoom": 22,
                        //     'paint': {
                        //         "raster-opacity": 1,
                        //     }
                        // },
                        //村界边缘
                        {
                            id: `nanhai_village-line-layer`,
                            source: `nanhai_village`,
                            "source-layer": `nanhai_village`,
                            type: "line",
                            layout: {
                                "line-cap": "round",
                                "line-join": "round",
                            },
                            paint: {
                                "line-color": "#ff0",
                                "line-opacity": 1,
                            },
                        },
                    ],
                },
            },
        };
    },
    mounted() {
        console.log(this.taskObject.pvCode);
        if (this.taskObject.pvCode && this.taskObject.pvCode === "P11101") {
            this.MapDefault();
        }
    },
    computed: {
        SearchMap() {
            let searchKey = [];
            if (localStorage.getItem("SYS_TYPE")) {
                this.SYS_TYPE = localStorage.getItem("SYS_TYPE");
                if (this.SYS_TYPE === "SS1") {
                    // 如果是渔业返回所有的渔业图斑
                    searchKey = ["==", "EJLX_CODE", "1104A"];
                } else {
                    // 如果是种植返回所有的除渔业以外的图斑
                    searchKey = ["!=", "EJLX_CODE", "1104A"];
                }
            }
            return searchKey;
        },
        ...mapState({
            taskObject: (state) => {
                return state.taskmodel.taskObject;
            },
            currentTask: (state) => {
                return state.currentTask.Task;
            },
            userInfo: (state) => {
                return state.User.userInfo;
            },
        }),
    },
    methods: {
        getSubject(subjectArray) {
            subjectArray.forEach((item) => {
                this.subjectData.push(item);
            });
        },
        collectSuccess() {
            this.LandParcelInfoVisible = false;
            this.random += 1;
        },
        experimentalDataAreaLayer(e) {
            if (e.target.className === "sm-components-icon-ploygon") {
                this["experimentalData-area-layer"] = !e.target.parentNode.classList.contains("is-active");
                if (this["experimentalData-area-layer"]) {
                    this.$message({
                        message: "当前已进入图斑框选模式，无法弹出图斑采集界面",
                        type: "warning",
                        duration: 2000,
                    });
                } else {
                    this.$message({
                        message: "当前已退出图斑框选模式，图斑采集工作恢复正常",
                        type: "success",
                        duration: 2000,
                    });
                }
            }
        },
        mapFilterState(obj) {
            this.spotstate = obj;
            setTimeout(() => {
                this.MapDefault();
            }, 5);
        },
        mapStateChange(obj) {

            if (obj.activeName) {
                this.activeName = obj.activeName;
            }
            if (obj.DKBHID) {
                this.DKBHID = obj.DKBHID;
            }
            if (obj.zoom) {
                this.zoom = obj.zoom;
            }
            if (obj.center) {
                this.center = obj.center;
            }
            if (obj.state && obj.state === "P11101") {
                this.isShow = true
                this.MapDefault();
            } else {
                this.isShow = false
            }
            if (obj.SearchMap) {
                this.SearchMapArray = obj.SearchMap;
                setTimeout(() => {
                    this.setMapFilter(obj.SearchMap);
                }, 100);
            }
        },
        guidance(index) {
            let msg = "";
            if (index === 0) {
                msg =
                    "任务栏中的采集中选中任务进入地图，筛选[图斑状态]为[未采集]的图斑进行数据标注即可。标注每个图斑后数据状态将变更为[已采集]。";
            } else {
                msg =
                    "任务栏中选择数据清单中进行[审核]或[批量审核]或者直接在GIS地图中点击图斑进行审核。";
            }
            this.$notify({
                title: "提示：您可以在左侧",
                message: msg,
                type: "success",
            });
        },
        MapDefault() {
            //默认加载图斑数据
            setTimeout(() => {
                let currentTask = this.currentTask.data;
                if (currentTask.treeData) {
                    let list = currentTask.treeData.list;
                    let xy = list.filter((item) => {
                        return item.latitude && item.dimensionality;
                    });
                    let latitude, dimensionality;

                    if (xy instanceof Array && xy.length) {
                        latitude = xy[0].latitude;
                        dimensionality = xy[0].dimensionality;
                    } else {
                        this.$message({
                            message: "村中心经纬度缺失,自动定位到区中心点",
                            type: "warning",
                            duration: 2500,
                        });
                        latitude = 113.0179631;
                        dimensionality = 23.059959;
                    }
                    let item = {
                        planId: currentTask.id,
                        taskArray: currentTask,
                        list: list,
                        center: [latitude, dimensionality],
                        status: "success",
                    };

                    this.getFilterMap(item);
                }
            }, 200);
        },
        tabClick() {
            if (this.activeName === "underwayend") {
                // this.params.isExpire = 1
                this.status = "underwayend";
            } else {
                this.status = "underway";
                // this.params.isExpire = 0
                // this.params.collectStatus = 1
            }
        },
        drawCreated(e) {
            console.log(e);
        },
        getFilterMap(item) {
            this.loading = true;
            let planId;
            if (item.planId) {
                planId = item.planId;
            } else {
                planId = item.id;
            }
            const loading = this.$loading({
                lock: true,
                text: "正在搜索图斑数据,请耐心等待",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
            });
            // 查询图斑
            let params = null;
            // 图斑初始状态
            params = {
                "collectTaskLand.planId": planId,
            };

            if (this.spotstate) {
                if (this.spotstate.auditStatus) {
                    params["collectTaskLand.auditStatus"] = this.spotstate.auditStatus;
                }
                if (this.spotstate.collectStatus) {
                    params["collectTaskLand.collectStatus"] =
                        this.spotstate.collectStatus;
                }
            }

            this.DKBHID = []; //保证搜索结果，每次搜索之前清空源数据
            this.$common.listPart(params).then((res) => {
                    // let DKBHIDTime = null;
                    if (res.errorCode === "00000") {
                        res.data.list.forEach((item) => {
                            this.DKBHID.push(item.landId);
                        });
                        setTimeout(() => {
                            this.center = item.center;
                            if (item.zoom) {
                                this.zoom = item.zoom;
                            }
                            if (this.spotstate) {
                                if (this.spotstate.collectStatus === 2) {
                                    this.zoom = 13;
                                    // this.label(this.DKBHID[2])
                                }
                            }
                            if (this.DKBHID.length) {
                                this.setMapFilter(["in", "DKBH", ...this.DKBHID]);
                            } else {
                                // this.$message({
                                //     message:"本次任务图斑搜索为0，请查看当前任务数据是否为空，或请手动重新选择任务",
                                //     type:"error",
                                //     duration:5000
                                // })
                                this.setMapFilter(this.SearchMap);
                            }
                            loading.close();
                            this.loading = false;
                        }, 5000);
                    }
                })
                .catch((err) => {
                    console.log(err);
                })
        },
        selectRegion(region) {
            this.zoom = 12
            this.center = region.center
            this.setMapFilter(region.filter);
        },
        setMapFilter(searchArray) {
            let fil = [];

            if (this.zoom != 15) {
                this.mapOptions.zoom = this.zoom;
            } else {
                this.mapOptions.zoom = 15;
            }

            fil[0] = this.SearchMap
            fil.push(searchArray);
            console.log(fil);

            this.map.setFilter("experimental-line-layer", ["all", ...fil]);
            this.map.setFilter("experimental-area-layer", ["all", ...fil]);
            setTimeout(() => {
                this.map.panTo(this.center);
            }, 500);
        },
        createArea(e) {
            //当前多边形的坐标点集合
            let current = e.features[0].geometry.coordinates[0];
            let scopeList = [];
            current.forEach((item) => {
                scopeList.push({
                    latitude: item[0],
                    longitude: item[1],
                });
            });
            let json = JSON.stringify({
                scopeList: scopeList,
            });
            //获取被框选的图斑

            axios({
                url: "https://api.leadinsight.cn/tianyan/api/v1/spot/spotCode",
                method: "post",
                headers: {
                    "Content-Type": "application/json;charset=UTF-8",
                },
                data: json,
            }).then((res) => {
                let data = res.data.data;
                if (data.length > 700) {
                    this.$message({
                        message: `框选工具最多只能选择500个图斑`,
                        type: "warning",
                    });
                    return false;
                } else if (data.length === 0) {
                    this.$message({
                        message: `您未选择任何图斑`,
                        type: "warning",
                    });
                    return false;
                } else {
                    let landID = '';
                    landID = res.data.data;
                    let landPlanId = "";
                    let currentTask = this.currentTask.data;
                    if (currentTask.id) {
                        landPlanId = currentTask.id;
                    } else {
                        this.$message({
                            message: `您必须选择一个任务`,
                            type: "warning",
                        });
                        return false;
                    }
                    this.$axios
                        .get("rbac/data/CollectTaskLand/list", {
                            params: {
                                pageNumber: 1,
                                pageSize: data.length,
                                landCodes: landID.join(","),
                                "collectTaskLand.planId": landPlanId,
                            },
                        })
                        .then((res) => {
                            this.maplandList = [];
                            if (res.errorCode === "00000") {
                                this.maplandList = res.data.list;
                                this.batchrandom = Math.random()
                                this.maplandListpage = {
                                    pageNum: res.data.pageNum,
                                    pageSize: res.data.pageSize,
                                    total: res.data.total,
                                    landCodes: landID.join(","),
                                    "collectTaskLand.planId": landPlanId,
                                };

                                setTimeout(() => {
                                    this.batchShow = true;
                                }, 0)
                            }
                        });
                }
            });
        },
        mapLoad(e) {
            this.map = e.map;
            this.map.on("draw.create", this.createArea);
            this.map.on("click", "experimental-area-layer", (e) => {
                if (this["experimentalData-area-layer"]) {
                    this.$message({
                        message: "当前已进入图斑框选模式，无法弹出图斑采集界面",
                        type: "warning",
                        duration: 2000,
                    });
                    return false;
                }
                e.preventDefault();
                console.log("e.features[0].properties:", e.features[0].properties);
                let properties = e.features[0].properties;

                let landPlanId = "",
                    landPlanName = "";
                let currentTask = this.currentTask.data;
                if (currentTask.id) {
                    // 任务模式
                    landPlanId = currentTask.id;
                    landPlanName = currentTask.planName;
                    this.currentDataTaskPlanName = '图斑信息采集 - ' + landPlanName + `(${landPlanId})`
                } else {
                    // 查看模式
                    this.currentDataTaskPlanName = '图斑信息采集 - 当前处于数据查看模式'
                }
                this.remoteSensingData = properties
                this.spotID = properties["DKBH"];
                console.log(this.spotID, this.remoteSensingData);
                this.LandParcelInfoVisible = true;
            });
        },

        label(DKBHID) {},
    },
};
</script>

<style lang="scss">
.map {
    height: calc(100vh - 60px);
    position: relative;

    .el-tab-pane {
        height: calc(100vh - 120px);
        overflow-y: auto;
    }

    .tool {
        display: flex;
        justify-content: space-between;
        align-items: center;

        div {
            display: flex;
            justify-content: space-between;

            .li {
                margin: 0 15px;
            }
        }

        .li {
            margin: 0 15px;
        }
    }

    .sm-web-map {
        position: relative;

        .map-state {
            padding: 0 20px 0 0;
            position: absolute;
            z-index: 2000;
            background: rgba(255, 255, 255, 0.7);
            color: #333;
            border: 5px solid #ddd;
            border-bottom-left-radius: 5px;
            border-bottom-right-radius: 5px;

            * {
                background: transparent;
                border: none;
                color: #333;
                font-size: 14px;
            }
        }
    }
}
</style>
